package com.huazai.apply.manager.web.action;

import com.huazai.apply.manager.bean.ApplyMessage;
import com.huazai.apply.manager.bean.User;
import com.huazai.apply.manager.dao.ApplyMapper;
import com.huazai.apply.manager.utils.MybatisUtil;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

/**
 * @author EZTTU
 */
@WebServlet(name = "Select", value = {"/admin", "/user"})
public class UserSelectServlet extends HttpServlet {
    private static final String SERVICE_ADMIN = "/admin";
    private static final String SERVICE_USER = "/user";

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
        HttpSession session = request.getSession();

        String servletPath = request.getServletPath();
        User userMessage = (User) session.getAttribute("UserMessage");

        if (servletPath.equals(SERVICE_ADMIN)) {

            if (userMessage.getUserField().equals("admin")) {
                doAdmin(request, response);
            } else {
                response.sendRedirect(request.getContextPath());
            }
        } else if (servletPath.equals(SERVICE_USER)) {

            if (userMessage.getUserField().equals("user")) {
                doOrdinary(request, response);
            } else {
                response.sendRedirect(request.getContextPath());
            }
        }
    }


    private void doAdmin(HttpServletRequest request, HttpServletResponse response) {

        try (SqlSession sqlSession = MybatisUtil.getSqlSession()) {
            ApplyMapper mapper = sqlSession.getMapper(ApplyMapper.class);
            List<ApplyMessage> messageList = mapper.getApplyById(null);

            request.setAttribute("MessageList", messageList);
            request.getRequestDispatcher("admin.jsp").forward(request, response);
        } catch (IOException | ServletException e) {
            e.printStackTrace();
        }

    }

    private void doOrdinary(HttpServletRequest request, HttpServletResponse response) {

        HttpSession session = request.getSession();
        User userMessage = (User) session.getAttribute("UserMessage");
        String userId = userMessage.getUserId();
        try (SqlSession sqlSession = MybatisUtil.getSqlSession()) {
            ApplyMapper mapper = sqlSession.getMapper(ApplyMapper.class);
            List<ApplyMessage> messageList = mapper.getApplyById(userId);

            request.setAttribute("MessageList", messageList);
            request.getRequestDispatcher("ordinary.jsp").forward(request, response);
        } catch (ServletException | IOException e) {
            e.printStackTrace();
        }
    }

}
